package logic

import (
	"context"
	"fmt"
	"house/cache"
	"house/houserpc/houserpc"
	"house/houserpc/internal/svc"
	"house/models"
	"house/pkg"
	"math/rand"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户注册
func (l *UserRegisterLogic) UserRegister(in *houserpc.UserRegisterRequest) (*houserpc.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line

	var user models.User
	models.DB.Debug().Where("account = ?", in.Account).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("当前账号已被注册")
	}

	result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if result != in.Captcha {
		return nil, fmt.Errorf("图形验证码错误")
	}

	result1, _ := cache.Rdb.Get(l.ctx, "sendSms = ?"+in.Account).Result()
	if result1 != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误")
	}

	user = models.User{
		Account:  in.Account,
		Password: pkg.Md5(in.Password),
		Image:    "https://ts1.tc.mm.bing.net/th/id/OIP-C.-rBqkricrrEXBZsFzjxtlQAAAA?rs=1&pid=ImgDetMain&o=7&rm=3",
		Name:     fmt.Sprintf("用户_%d", rand.Intn(10000)),
	}
	models.DB.Debug().Create(&user)

	return &houserpc.UserRegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
